package com.qipay.api.home.controller;

import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.utils.ResultUtils;
import com.qipay.utils.XmlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@ControllerAdvice
public class GlobalErrorController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String jsonErrorHandler(HttpServletRequest req,
                                   Exception e) throws Exception {
        Map<String, Object> result =
                ResultUtils.createStatusResult(ApiStatusEnum.SERVICE_ERR.getCode().toString(),
                        ApiStatusEnum.SERVICE_ERR.getInfo());
        logger.error("API请求出错", e);
//        response.setContentType("application/xml;charset=UTF-8");
        return XmlUtils.toString(result, "xml");
    }

    @ExceptionHandler(value = {IllegalArgumentException.class, IllegalStateException.class})
    @ResponseBody
    public String AssertErrorHandler(HttpServletRequest req,
                                     Exception e) throws Exception {
        String errorMsg = e.getMessage();
        ApiStatusEnum apiStatusEnum = ResultUtils.getApiType(errorMsg, ApiStatusEnum.ARGUMENT_REQUEST);
        errorMsg = ResultUtils.getErrorMsg(errorMsg);
        Map<String, Object> result =
                ResultUtils.createStatusResult(apiStatusEnum.getCode().toString(),
                        errorMsg);
        return XmlUtils.toString(result, "xml");
    }

}
